package org.jwos.plugin.file.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jwos.platform.domain.User;
import org.jwos.platform.service.SessionManager;
import org.jwos.plugin.file.domain.FileInfo;
import org.jwos.plugin.file.service.FileManager;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import sun.net.www.MimeTable;

public class FileDownloadServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		String sessionId = request.getParameter("sessionId");
		String fileId = request.getParameter("FileID")!=null ? request.getParameter("FileID") : request.getParameter("id");
		String att = request.getParameter("att");
		boolean thumbnail = request.getParameter("thumbnail")!=null && request.getParameter("thumbnail").equals("true");
		
		BufferedInputStream bis  = null; 
        BufferedOutputStream bos = null; 
		try {
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
			FileManager service = (FileManager)context.getBean("fileManager");
			FileInfo file = service.getFileInfoById(sessionId,fileId);			
			
			if(file==null) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND);
				return;
			} else if(!file.isPublished() && !service.isFileInPublishedFolder(fileId)) {
				if(sessionId==null) {
					response.sendError(HttpServletResponse.SC_FORBIDDEN);
					return;
				} else {
					SessionManager sessionManager = (SessionManager)context.getBean("sessionManager");
					User user = sessionManager.getUserBySessionId(sessionId);
					if(user==null) {
						response.sendError(HttpServletResponse.SC_FORBIDDEN);
						return;
					}
				}
			}			
			
			String fileName = file.getName();
			if(thumbnail) {
				fileName = "thumbnail.jpg";				
			}			
			MimeTable mt = MimeTable.getDefaultTable();
			String mimeType = mt.getContentTypeFor(fileName);
			if (mimeType == null) {
				mimeType = "application/octet-stream";
			}
        	
	        response.reset();
			response.setContentType(mimeType);
			fileName = URLEncoder.encode(fileName,"UTF-8");
			response.setHeader("Content-disposition","attachment;filename=\""+fileName+"\"");
	    	response.resetBuffer();
	    	
	    	bis = new BufferedInputStream(thumbnail ? service.getFileThumbnailById(sessionId, fileId) : service.getFileContentById(sessionId,fileId));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bos.flush();
			bos.close();
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		} finally {
        	try {
				if (bis != null)
					bis.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
        }	
	}
}
